package com.atguigu.flink0922.chapter02;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.*;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/1 9:38
 */
public class BatchWordCount {
    public static void main(String[] args) throws Exception {
        // 批处理
        // 1. 获取执行环境
        final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        // 2. 从文件读取数据, 得到一个DataSet
        final DataSource<String> sourceSet = env.readTextFile("input/words.txt");
        // 3. 对DataSet做各种转换
        final FlatMapOperator<String, String> words = sourceSet
            .flatMap(new FlatMapFunction<String, String>() {
                @Override
                public void flatMap(String line, Collector<String> out) throws Exception {
                    final String[] words = line.split(" ");
                    for (String word : words) {
                        
                        out.collect(word);
                    }
                }
            });
        final MapOperator<String, Tuple2<String, Long>> wordOne = words.map(new MapFunction<String, Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> map(String word) throws Exception {
                return Tuple2.of(word, 1L);
            }
        });
    
        final UnsortedGrouping<Tuple2<String, Long>> grouped = wordOne.groupBy(0);
    
        final AggregateOperator<Tuple2<String, Long>> result = grouped.sum(1);
        
        // 4. 输出结果
        result.print();
        
    }
}
